package com.realjinge.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.realjinge.entity.Answer;
import com.realjinge.entity.Question;
import com.realjinge.entity.Type;
import com.realjinge.entity.WeChatUser;
import com.realjinge.service.AnswerService;
import com.realjinge.service.QuestionService;
import com.realjinge.service.TypeService;
import com.realjinge.service.WeChatUserService;
import com.realjinge.utils.ErrorCodeUtils;

@Controller
@RequestMapping("/question")
public class QuestionController {
	@Resource
	private TypeService typeService;
	@Resource
	private QuestionService questionService;
	@Resource
	private AnswerService answerService;
	@Resource
	private WeChatUserService weChatUserService;

	@RequestMapping(value = "/addQuestion.do")
	public String addQuestion(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		String token = request.getParameter("token");
		if (null == token || "".equals(token)) {
			token = (String) request.getSession().getAttribute("token");
		}
		map.put("token", token);
		List<Type> list = typeService.selectTypeList();
		map.put("typeList", list);
		return "view/question/addQuestion";
	}

	@RequestMapping(value = "/insetQuestion.do")
	public String insertQuestion(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		String typeCode = request.getParameter("typeCode");
		String questionContent = request.getParameter("questionContent");
		String answerA = request.getParameter("answerA");
		String answerB = request.getParameter("answerB");
		String answerC = request.getParameter("answerC");
		String answerD = request.getParameter("answerD");
		String answer = request.getParameter("answer");
		String questionDesc = request.getParameter("questionDesc");
		String jsonMsg = "";
		if (typeCode != null && !"".equals(typeCode) && questionContent != null && !"".equals(questionContent)
				&& answer != null && !"".equals(answer) && answerA != null && !"".equals(answerA) && answerB != null
				&& !"".equals(answerB) && answerC != null && !"".equals(answerC) && answerD != null
				&& !"".equals(answerD)) {
			String questionNo = "TM-" + typeCode + "-" + System.currentTimeMillis() + "-ENDSIGN";
			Question question = questionService.selectQuestionByQuestionNo(questionNo);
			if (question == null) {
				String token = request.getParameter("token");
				if (null == token || "".equals(token)) {
					token = (String) request.getSession().getAttribute("token");
				}
				map.put("token", token);
				String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				String editTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				question = new Question(typeCode, questionNo, questionContent, answer, questionDesc, "01", token,
						createTime, token, editTime);
				Integer ret = questionService.insertQuestion(question);
				if (ret > 0) {
					Integer questionId = question.getId();
					Answer A = new Answer(questionId, questionNo, answerA);
					answerService.insertAnswer(A);
					Answer B = new Answer(questionId, questionNo, answerB);
					answerService.insertAnswer(B);
					Answer C = new Answer(questionId, questionNo, answerC);
					answerService.insertAnswer(C);
					Answer D = new Answer(questionId, questionNo, answerD);
					answerService.insertAnswer(D);

					Integer answerId = 0;
					if ("01".equals(answer)) {
						answerId = A.getId();
					} else if ("02".equals(answer)) {
						answerId = B.getId();
					} else if ("03".equals(answer)) {
						answerId = C.getId();
					} else if ("04".equals(answer)) {
						answerId = D.getId();
					}
					try {
						System.out.println("answerId:\t" + answerId);
						// questionService.updateQuestionAnswerBYID(String.valueOf(answerId),
						// questionId);
						questionService.updateQuestionAnswerBYQuestionNo(String.valueOf(answerId), questionNo);
						map.put("question", question);
						jsonMsg = ErrorCodeUtils.errCode0();
					} catch (Exception e) {
						jsonMsg = ErrorCodeUtils.errCode1();
						e.printStackTrace();
					}
				} else {
					jsonMsg = ErrorCodeUtils.errCode("20103", "题目新增失败");
				}
			} else {
				jsonMsg = ErrorCodeUtils.errCode("20102", "题目编号已存在");
			}
		} else {
			jsonMsg = ErrorCodeUtils.errCode("20101", "题目必要参数不能为空");
		}
		// out(response, jsonMsg);
		map.put("msg", jsonMsg);
		return "view/question/success";
	}

	@RequestMapping(value = "/preview.do")
	public String preview(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		String token = request.getParameter("token");
		if (null == token || "".equals(token)) {
			token = (String) request.getSession().getAttribute("token");
		}
		map.put("token", token);
		String questionNo = request.getParameter("questionNo");
		Question question = questionService.selectQuestionByQuestionNo(questionNo);
		List<Type> list = typeService.selectTypeList();
		map.put("typeList", list);
		map.put("question", question);
		return "view/question/preview";
	}

	@RequestMapping(value = "/questionList.do")
	public String toQuestionList(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		String token = request.getParameter("token");
		if (null == token || "".equals(token)) {
			token = (String) request.getSession().getAttribute("token");
		}
		map.put("token", token);
		List<Type> list = typeService.selectTypeList();
		map.put("typeList", list);
		// List<Question> questions = questionService.selectQuestionList();
		List<Question> questions = questionService.selectQuestionListByCreator(token);
		map.put("questionList", questions);
		return "view/question/questionList";
	}

	@RequestMapping(value = "/singleAnswer.do")
	public String toSingleAnswer(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		String token = request.getParameter("token");
		if (null == token || "".equals(token)) {
			token = (String) request.getSession().getAttribute("token");
		}
		map.put("token", token);
		String startNumStr = request.getParameter("startNum");
		String rightNumStr = request.getParameter("rightNum");
		if (startNumStr == null || "".equals(startNumStr)) {
			startNumStr = "0";
		}
		if (rightNumStr == null || "".equals(rightNumStr)) {
			rightNumStr = "0";
		}
		Integer startNum = Integer.parseInt(startNumStr);
		map.put("startNum", startNum);
		Integer rightNum = Integer.parseInt(rightNumStr);
		map.put("rightNum", rightNum);
		Integer endNum = startNum + 1;
		// List<Question> questions = questionService.selectQuestionPage(startNum, endNum);
		// if (questions != null && !questions.isEmpty()) {
		if (endNum <= 12) {
			List<Type> list = typeService.selectTypeList();
			map.put("typeList", list);
			List<Question> temp = new ArrayList<Question>();
			Question question = questionService.selectQuestionByTypeCode("CCTV_" + endNum);
			// temp.add(questions.get(0));
			if (question != null) {
				temp.add(question); 
			} else {
				map.put("msg", "共答对 " + rightNum + " 题！");
				// return "view/index";
				WeChatUser user = weChatUserService.getWeChatUser(token);
				map.put("user", user);
				return "view/question/result";
			}
			map.put("questionList", temp);
			return "view/question/singleAnswer";
		} else {
			map.put("msg", "共答对 " + rightNum + " 题！");
			// return "view/index";
			WeChatUser user = weChatUserService.getWeChatUser(token);
			map.put("user", user);
			return "view/question/result";
		}
	}

	@RequestMapping(value = "/doubleAnswer.do")
	public String toDoubleAnswer(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		String token = request.getParameter("token");
		if (null == token || "".equals(token)) {
			token = (String) request.getSession().getAttribute("token");
		}
		map.put("token", token);
		List<Type> list = typeService.selectTypeList();
		map.put("typeList", list);
		return "view/question/doubleAnswer";
	}

	/**
	 * 输出JSON字符串
	 * 
	 * @param response
	 * @param jsonMsg
	 */
	protected void out(HttpServletResponse response, String jsonMsg) {
		try {
			response.setContentType("text/json;charset=utf-8");
			response.getWriter().write(jsonMsg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
